package me.zhengjie.modules.insurance.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 城市数据
 *
 * @author HeHui
 * @date 2022-01-08 14:25
 */
@Component
public class CityHandler {

    private final Map<String, String> cityMap;

    public CityHandler(ResourceLoader resourceLoader) throws IOException {
        String json = IoUtil.read(resourceLoader.getResource("classpath:city_names.json").getInputStream(), "utf-8");
        if (JSONUtil.isJsonArray(json)) {
            cityMap = (Map) Collections.unmodifiableMap(JSONUtil.parseArray(json).toList(Map.class).stream().collect(Collectors.toMap(v -> v.getOrDefault("id",""), v -> v.getOrDefault("name",""),(v1, v2) -> v1)));
        } else {
            cityMap = Collections.emptyMap();
        }
    }



    public String getName(String codes) {
        if (StrUtil.isBlank(codes)) {
            return "";
        }

        return Arrays.stream(codes.split(",")).map(Integer::valueOf).filter(cityMap::containsKey).map(cityMap::get).collect(Collectors.joining(","));
    }
}
